package com.wejoy.video.middle.station.api.controller.workorder;

import com.wejoy.video.middle.station.api.annotation.LoginCheck;
import com.wejoy.video.middle.station.data.annotation.RoleCheck;
import com.wejoy.video.middle.station.data.domain.PageResult;
import com.wejoy.video.middle.station.data.domain.system.SysUser;
import com.wejoy.video.middle.station.data.domain.workorder.OrderPhotoLib;
import com.wejoy.video.middle.station.data.domain.workorder.WorkOrderInfo;
import com.wejoy.video.middle.station.data.domain.workorder.WorkOrderProcess;
import com.wejoy.video.middle.station.data.domain.workorder.WorkOrderReview;
import com.wejoy.video.middle.station.data.enums.dict.EnumWorkOrderStatus;
import com.wejoy.video.middle.station.data.exception.BusinessException;
import com.wejoy.video.middle.station.data.service.workorder.IOrderPhotoLibService;
import com.wejoy.video.middle.station.data.service.workorder.IWorkOrderInfoService;
import com.wejoy.video.middle.station.data.service.workorder.IWorkOrderProcessService;
import com.wejoy.video.middle.station.data.service.workorder.IWorkOrderReviewService;
import com.wejoy.video.middle.station.data.util.LoginUtil;
import com.wejoy.video.middle.station.data.util.StringUtils;
import com.wejoy.video.middle.station.data.util.WJAssert;
import com.wejoy.video.middle.station.data.vo.RespJSON;
import com.wejoy.video.middle.station.data.vo.workorder.WorkOrderDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RequestMapping("/workorder/workOrderInfo")
@RestController
public class WorkOrderAction {

    @Autowired
    private IWorkOrderInfoService workOrderInfoService;
    @Autowired
    private IWorkOrderProcessService workOrderProcessService;
    @Autowired
    private IWorkOrderReviewService workOrderReviewService;
    @Autowired
    private IOrderPhotoLibService orderPhotoLibService;

    /**
     * 分页查询
     *
     * @param workOrderInfoReq workOrderInfoReq
     * @return RespJSON
     */
    @PostMapping("/getPageList")
    @LoginCheck
    public RespJSON getPageList(@RequestBody WorkOrderInfo workOrderInfoReq,@SessionAttribute(value = LoginUtil.LOGIN_USER_SESSION_KEY) SysUser loginSysUser) {
        if(!CollectionUtils.isEmpty(loginSysUser.getDataPermissionDeptIds())&&loginSysUser.getDataPermissionDeptIds().size()==1&&loginSysUser.getDataPermissionDeptIds().get(0)==3){
            int count = workOrderInfoService.getCount(workOrderInfoReq);
            List<WorkOrderInfo> list = new ArrayList<>();
            if (count > 0) {
                list = workOrderInfoService.getPageList(workOrderInfoReq);
                list.parallelStream().forEach(item -> {
                    item.setOrderButton(loginSysUser.getSysResourceIdentityList().contains("work_order_accept"));
                    item.setApprovalButton(loginSysUser.getSysResourceIdentityList().contains("work_order_review"));
                    item.setReminderButton(loginSysUser.getSysResourceIdentityList().contains("work_order_remind"));
                    if(item.getOrderStatus().equals(EnumWorkOrderStatus.ACCEPT_UNPROCESSED.getCode())||item.getOrderStatus().equals(EnumWorkOrderStatus.ACCEPT_PREPROCESSING.getCode())){
                        item.setCanHandle(item.getAcceptUserId().equals(loginSysUser.getId()));
                    }
                });
            }
            PageResult result = new PageResult(workOrderInfoReq.getPageNo(), workOrderInfoReq.getPageSize(), count, list);
            return RespJSON.success(result);
        }else{
            if(CollectionUtils.isEmpty(loginSysUser.getDataPermissionDeptIds())){
                return RespJSON.success();
            }
            workOrderInfoReq.setDataPermissionDeptIds(loginSysUser.getDataPermissionDeptIds());
            int count = workOrderInfoService.getDataPermissionCount(workOrderInfoReq);
            List<WorkOrderInfo> list = new ArrayList<>();
            if (count > 0) {
                list = workOrderInfoService.getDataPermissionPageList(workOrderInfoReq);
                list.parallelStream().forEach(item -> {
                    item.setOrderButton(loginSysUser.getSysResourceIdentityList().contains("work_order_accept"));
                    item.setApprovalButton(loginSysUser.getSysResourceIdentityList().contains("work_order_review"));
                    item.setReminderButton(loginSysUser.getSysResourceIdentityList().contains("work_order_remind"));
                    if(item.getOrderStatus().equals(EnumWorkOrderStatus.ACCEPT_UNPROCESSED.getCode())||item.getOrderStatus().equals(EnumWorkOrderStatus.ACCEPT_PREPROCESSING.getCode())){
                        item.setCanHandle(item.getAcceptUserId().equals(loginSysUser.getId()));
                    }
                });
            }
            PageResult result = new PageResult(workOrderInfoReq.getPageNo(), workOrderInfoReq.getPageSize(), count, list);
            return RespJSON.success(result);
        }
    }

    /**
     * 工单详情，查询处置列表+审核列表
     * @return
     */
    @GetMapping("/getDetail")
    @LoginCheck
    public RespJSON getDetail(Long id,@SessionAttribute(value = LoginUtil.LOGIN_USER_SESSION_KEY) SysUser loginSysUser) {
        WJAssert.notNull(id, "ID 不合法");
        WorkOrderInfo workOrderInfo = workOrderInfoService.getOneById(id);
        WJAssert.notNull(workOrderInfo, "ID 不合法");
        OrderPhotoLib orderPhotoLib = new OrderPhotoLib();
        orderPhotoLib.setOrderId(id);
        List<OrderPhotoLib> list = orderPhotoLibService.getList(orderPhotoLib);
        workOrderInfo.setPhotoLibs(list);
        WorkOrderProcess processWhere = new WorkOrderProcess();
        processWhere.setOrderId(id);
        List<WorkOrderProcess> list1 = workOrderProcessService.getList(processWhere);
        for (WorkOrderProcess workOrderProcess : list1) {
            if(!StringUtils.isEmpty(workOrderProcess.getImgPath())){
                workOrderProcess.setPreviewImgPathList(Arrays.asList(workOrderProcess.getImgPath().split(",")));
            }
        }
        workOrderInfo.setProcessList(list1);
        WorkOrderReview reviewWhere = new WorkOrderReview();
        reviewWhere.setOrderId(id);
        workOrderInfo.setReviewList(workOrderReviewService.getList(reviewWhere));
        workOrderInfo.setOrderButton(loginSysUser.getSysResourceIdentityList().contains("work_order_accept"));
        workOrderInfo.setApprovalButton(loginSysUser.getSysResourceIdentityList().contains("work_order_review"));
        workOrderInfo.setReminderButton(loginSysUser.getSysResourceIdentityList().contains("work_order_remind"));
        if(workOrderInfo.getOrderStatus().equals(EnumWorkOrderStatus.ACCEPT_UNPROCESSED.getCode())||workOrderInfo.getOrderStatus().equals(EnumWorkOrderStatus.ACCEPT_PREPROCESSING.getCode())){
            workOrderInfo.setCanHandle(workOrderInfo.getAcceptUserId().equals(loginSysUser.getId()));
        }
        return RespJSON.success(workOrderInfo);
    }

    /**
     * 催单
     * @param id id
     * @return RespJSON
     */
    @GetMapping("/reminders")
    public RespJSON reminders(Long id, @SessionAttribute(value = LoginUtil.LOGIN_USER_SESSION_KEY) SysUser loginSysUser) {
        WJAssert.notNull(id, "ID 不合法");
        if(!workOrderInfoService.canItBeUrged(id,loginSysUser.getId())){
            throw new BusinessException("此任务单已经催过单了，请稍后重试！");
        }
        workOrderInfoService.reminders(id, loginSysUser.getName(),loginSysUser.getId());
        return RespJSON.success();
    }

    /**
     * 接单
     * @param workOrderInfo id
     * @return RespJSON
     */
    @PostMapping("/acceptOrder")
    public RespJSON acceptOrder(@RequestBody WorkOrderInfo workOrderInfo, @SessionAttribute(value = LoginUtil.LOGIN_USER_SESSION_KEY) SysUser loginSysUser) {
        WJAssert.notNull(workOrderInfo, "参数不合法");
        WJAssert.notNull(workOrderInfo.getId(), "ID 不合法");
        boolean workOrderAccept = loginSysUser.getSysResourceIdentityList().contains("work_order_accept");
        if(!workOrderAccept){
            throw new BusinessException("无此权限！");
        }
        workOrderInfoService.acceptOrder(workOrderInfo.getId(), loginSysUser);
        return RespJSON.success();
    }

    /**
     * 保存处置详情
     *
     * @param workOrderProcessReq workOrderProcessReq
     * @return RespJSON
     */
    @PostMapping("/saveProcess")
    public RespJSON saveProcess(@RequestBody WorkOrderProcess workOrderProcessReq, @SessionAttribute(value = LoginUtil.LOGIN_USER_SESSION_KEY) SysUser loginSysUser) {
        workOrderProcessReq.setUserPhone(Long.valueOf(loginSysUser.getTel()));
        workOrderProcessReq.setUserId(loginSysUser.getId());
        workOrderProcessService.save(workOrderProcessReq, loginSysUser.getName(),loginSysUser.getId());
        return RespJSON.success();
    }

    /**
     * 保存审核详情
     *
     * @param workOrderReviewReq workOrderReviewReq
     * @return RespJSON
     */
    @PostMapping("/saveReview")
    public RespJSON saveReview(@RequestBody WorkOrderReview workOrderReviewReq, @SessionAttribute(value = LoginUtil.LOGIN_USER_SESSION_KEY) SysUser loginSysUser) {
        workOrderReviewReq.setUserPhone(Long.valueOf(loginSysUser.getTel()));
        workOrderReviewService.save(workOrderReviewReq, loginSysUser.getName());
        return RespJSON.success();
    }

}
